package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.hmdp.dto.UserDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

/**
 * ClassName: RefreshTokenInterceptor
 * Package: com.hmdp.utils
 * Description:
 *
 * @Author: 葛龙
 * @Create 2025/3/18 14:07
 * @Version 1.0
 */
@Component
@RequiredArgsConstructor
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 该前置拦截器用于获取token，将用户存到threadlocal中，并刷新token
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头的token
        final String token = request.getHeader("authorization");
        String userToken = LOGIN_USER_KEY + token;

        if (StrUtil.isBlank(token)){
            //token为空 说明用户不存在 不需要刷新 直接放行
            return true;
        }
        //基于token获取redis中的用户
        final Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(userToken);

        if (userMap.isEmpty()) {
            //token为空 说明用户未登录 不需要刷新 直接放行
            return true;
        }


       UserDTO userDTO =  BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        //将userDTO保存在threadlocal中
        UserHolder.saveUser(userDTO);

        //刷新redis存储时间
        stringRedisTemplate.expire(userToken, LOGIN_USER_TTL , TimeUnit.SECONDS);

        //放行
        return true;
    }

}
